package com.it2297.util;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.RasterFormatException;

public class ImageProcessor
{
	public static BufferedImage resize(BufferedImage bimg, int width, int height, boolean lockWidth, boolean lockHeight)
	{
		double widthRatio = (double) width / bimg.getWidth();
		double heightRatio = (double) height / bimg.getHeight();

		AffineTransform transform = new AffineTransform();

		if (lockWidth && lockHeight)
		{
			double minRatio;
			if (widthRatio > heightRatio)
			{
				minRatio = heightRatio;
			}
			else
			{
				minRatio = widthRatio;
			}
			transform.scale(minRatio, minRatio);
		}
		else if (lockWidth)
		{
			transform.scale(widthRatio, widthRatio);
		}
		else if (lockHeight)
		{
			transform.scale(heightRatio, heightRatio);
		}
		else
		{
			transform.scale(widthRatio, heightRatio);
		}

		AffineTransformOp transformOp;
		if (widthRatio > 1 || heightRatio > 1)
		{
			transformOp = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC);
		}
		else
		{
			transformOp = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
		}

		return transformOp.filter(bimg, null);

	}

	public static BufferedImage cropImage(BufferedImage bimg, int x, int y, int width, int height) throws RasterFormatException
	{
		return bimg.getSubimage(x, y, width, height);
	}
}
